<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>风速监测系统</title>
    <!-- Tailwind CSS -->
    <link href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css" rel="stylesheet">
    <!-- Font Awesome -->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css" rel="stylesheet">
    <!-- ECharts -->
    <script src="https://cdn.jsdelivr.net/npm/echarts@5.4.0/dist/echarts.min.js"></script>
    <!-- Particles.js -->
    <script src="https://cdn.jsdelivr.net/npm/particles.js@2.0.0/particles.min.js"></script>
    <!-- SVG地图脚本 -->
    <script src="svgMap.js"></script>
    <style>
        :root {
            --blue: #3B82F6;
            --green: #10B981;
            --red: #EF4444;
            --yellow: #F59E0B;
            --purple: #8B5CF6;
            --gray: #6B7280;
        }
        
        body {
            font-family: 'Inter', system-ui, -apple-system, sans-serif;
            background-color: #111827;
            color: #F9FAFB;
        }
        
        #particles-js {
            position: fixed;
            width: 100%;
            height: 100%;
            top: 0;
            left: 0;
            z-index: -1;
        }
        
        .map-container {
            min-height: 300px;
        }
        
        .station-card {
            transition: all 0.3s ease;
            position: relative;
            overflow: hidden;
        }
        
        .station-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.5);
        }
        
        .station-card::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            width: 4px;
            height: 100%;
        }
        
        .map-mode-switch {
            position: absolute;
            top: 10px;
            right: 10px;
            background-color: rgba(0, 0, 0, 0.7);
            border-radius: 8px;
            padding: 5px;
            display: flex;
            z-index: 50;
        }
        
        .map-mode-btn {
            padding: 5px 10px;
            margin: 0 2px;
            cursor: pointer;
            border-radius: 4px;
            color: #fff;
            font-size: 12px;
        }
        
        .map-mode-btn:hover {
            background-color: rgba(255, 255, 255, 0.2);
        }
        
        .map-mode-btn.active {
            background-color: var(--blue);
        }
        
        .alert-pulse {
            animation: pulse 2s infinite;
        }
        
        @keyframes pulse {
            0% {
                box-shadow: 0 0 0 0 rgba(239, 68, 68, 0.7);
            }
            70% {
                box-shadow: 0 0 0 10px rgba(239, 68, 68, 0);
            }
            100% {
                box-shadow: 0 0 0 0 rgba(239, 68, 68, 0);
            }
        }
        
        /* 自定义滚动条 */
        ::-webkit-scrollbar {
            width: 8px;
            height: 8px;
        }
        
        ::-webkit-scrollbar-track {
            background: #1F2937;
        }
        
        ::-webkit-scrollbar-thumb {
            background: #4B5563;
            border-radius: 4px;
        }
        
        ::-webkit-scrollbar-thumb:hover {
            background: #6B7280;
        }
    </style>
</head>
<body class="min-h-screen">
    <!-- 粒子背景 -->
    <div id="particles-js"></div>
    
    <!-- 主容器 -->
    <div class="container mx-auto px-4 py-8">
        <!-- 头部 -->
        <header class="mb-6 flex justify-between items-center">
            <div>
                <h1 class="text-3xl font-bold text-white flex items-center">
                    <i class="fas fa-wind mr-3 text-blue-500"></i>
                    风速监测系统
            </h1>
                <p class="text-gray-400 mt-1" id="current-time">更新时间: 加载中...</p>
            </div>
            <div class="flex space-x-2">
                <button id="debug-btn" class="px-3 py-2 bg-gray-700 hover:bg-gray-600 text-white rounded-md flex items-center">
                    <i class="fas fa-bug mr-2"></i>调试
                </button>
                <button id="refresh-btn" class="px-3 py-2 bg-blue-600 hover:bg-blue-500 text-white rounded-md flex items-center">
                    <i class="fas fa-sync-alt mr-2"></i>刷新
                </button>
                <button id="mock-data-btn" class="px-3 py-2 bg-purple-600 hover:bg-purple-500 text-white rounded-md flex items-center">
                    <i class="fas fa-random mr-2"></i>模拟数据
                </button>
            </div>
        </header>

        <!-- 主要内容区域 -->
        <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
            <!-- 左侧 - 站点分布图 -->
            <div class="lg:col-span-2">
                <div class="bg-gray-800 rounded-lg p-4 shadow-lg mb-6">
                    <h2 class="text-xl font-bold mb-4">站点分布</h2>
                    <div id="map-container" class="w-full h-96 relative rounded-lg overflow-hidden bg-gray-900 map-container">
                        <div class="absolute inset-0 flex items-center justify-center">
                            <div class="text-center">
                                <i class="fas fa-spinner fa-spin text-3xl"></i>
                                <p class="mt-2">正在加载地图...</p>
                </div>
            </div>
                </div>
                    </div>
                </div>
            
            <!-- 右侧 - 风速报警 -->
            <div>
                <div class="bg-gray-800 rounded-lg p-4 shadow-lg mb-6">
                    <h2 class="text-xl font-bold mb-4">风速报警</h2>
                    <div id="alert-container" class="max-h-96 overflow-y-auto">
                        <div class="text-center text-gray-500 py-4">
                            <i class="fas fa-spinner fa-spin mr-2"></i>
                            正在加载数据...
                        </div>
                </div>
            </div>
        </div>

            <!-- 风速趋势 -->
            <div class="lg:col-span-3">
                <div class="bg-gray-800 rounded-lg p-4 shadow-lg mb-6">
            <div class="flex justify-between items-center mb-4">
                        <h2 class="text-xl font-bold">风速趋势</h2>
                <div class="flex space-x-2">
                            <select id="time-selector" class="bg-gray-700 text-white rounded-md px-3 py-1">
                                <option value="hour">最近1小时</option>
                                <option value="day" selected>最近24小时</option>
                                <option value="week">最近7天</option>
                    </select>
                </div>
            </div>
                    <div id="trend-chart" class="w-full h-80 relative">
                        <div class="absolute inset-0 flex items-center justify-center">
                            <div class="text-center">
                                <i class="fas fa-spinner fa-spin text-3xl"></i>
                                <p class="mt-2">正在加载图表...</p>
                            </div>
                        </div>
                    </div>
            </div>
        </div>

            <!-- 站点卡片区域 -->
            <div class="lg:col-span-3">
                <h2 class="text-xl font-bold mb-4">站点信息</h2>
                <div id="station-cards" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
                    <div class="text-center text-gray-500 py-4 col-span-full">
                        <i class="fas fa-spinner fa-spin mr-2"></i>
                        正在加载站点数据...
                    </div>
                </div>
        </div>
    </div>

        <!-- 底部 -->
        <footer class="mt-8 text-center text-gray-500 text-sm">
            <p>© 2023 风速监测系统 | 版本 1.0.0</p>
            <p class="mt-1">
                <span id="connection-status" class="inline-flex items-center">
                    <i class="fas fa-circle text-yellow-500 mr-1 text-xs"></i>
                    正在连接...
                </span>
            </p>
        </footer>
    </div>
    
    <!-- 脚本部分 -->
    <script>
        // 全局应用数据
        const appData = {
            stations: {},
            stationData: {},
            alerts: [],
            websocket: null,
            timeRange: 'day',
            echartsLoaded: false,
            echartsInstance: null
        };

        // 页面初始化
        function initPage() {
            console.group('初始化页面');
            console.log('正在初始化风速监测系统...');
            
            // 显示加载状态
            document.getElementById('station-cards').innerHTML = `
                <div class="text-center text-gray-500 py-4 col-span-full">
                    <i class="fas fa-spinner fa-spin mr-2"></i>
                    正在加载站点数据...
                </div>
            `;
            
            // 初始化调试按钮
            document.getElementById('debug-btn').addEventListener('click', () => {
                console.group('调试信息');
                console.log('应用数据:', appData);
                console.log('连接状态:', appData.websocket ? appData.websocket.readyState : '未连接');
                console.log('数据点数:', Object.values(appData.stationData).reduce((acc, curr) => acc + curr.length, 0));
                console.log('报警数:', appData.alerts.length);
                console.groupEnd();
                alert('调试信息已输出到控制台');
            });
            
            // 初始化刷新按钮
            document.getElementById('refresh-btn').addEventListener('click', () => {
                loadStationData()
                    .then(() => {
                        alert('数据已刷新');
                    })
                    .catch(err => {
                        console.error('刷新数据失败:', err);
                        alert('刷新失败，已使用模拟数据');
                        generateMockData();
                    });
            });
            
            // 初始化模拟数据按钮
            document.getElementById('mock-data-btn').addEventListener('click', () => {
                generateMockData();
                createStationCards();
                alert('已生成模拟数据');
            });
            
            // 初始化时间选择器
            document.getElementById('time-selector').addEventListener('change', function() {
                appData.timeRange = this.value;
                updateTrendChart();
            });
            
            // 尝试加载站点数据
            loadStationData()
                .then(() => {
                    // 数据加载成功后，建立WebSocket连接
                    setupWebSocket();
                })
                .catch(err => {
                    console.error('加载站点数据失败:', err);
                    // 加载失败时使用模拟数据
                    generateMockData();
                    setupWebSocket();
                });
            
            // 尝试加载地图
            loadMap();
            
            console.log('页面初始化完成');
            console.groupEnd();
        }
        
        // 加载站点数据
        async function loadStationData() {
            console.log('正在加载站点数据...');
            
            try {
                // 获取站点列表
                const stationsResponse = await fetch('/api/stations');
                if (!stationsResponse.ok) throw new Error('无法获取站点列表');
                
                const stations = await stationsResponse.json();
                appData.stations = {};
                
                // 转换为对象格式
                stations.forEach(station => {
                    appData.stations[station.id] = station;
                });
                
                // 获取每个站点的风速数据
                const stationIds = Object.keys(appData.stations);
                appData.stationData = {};
                
                // 获取时间范围参数
                const timeRange = document.getElementById('time-selector').value;
                
                for (const stationId of stationIds) {
                    const dataResponse = await fetch(`/api/wind-data/${stationId}?range=${timeRange}`);
                    if (!dataResponse.ok) throw new Error(`无法获取站点 ${stationId} 的数据`);
                    
                    const stationData = await dataResponse.json();
                    appData.stationData[stationId] = stationData;
                }
                
                // 获取报警数据
                const alertsResponse = await fetch('/api/alerts');
                if (!alertsResponse.ok) throw new Error('无法获取报警数据');
                
                appData.alerts = await alertsResponse.json();
                
                // 更新UI
                createStationCards();
                updateAlerts();
                updateTrendChart();
                
                console.log('站点数据加载完成');
                return true;
                
            } catch (error) {
                console.error('加载站点数据失败:', error);
                throw error;
            }
        }
        
        // 建立WebSocket连接
        function setupWebSocket() {
            console.log('正在建立WebSocket连接...');
            
            const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
            const wsUrl = `${protocol}//${window.location.host}/ws`;
            
            try {
                appData.websocket = new WebSocket(wsUrl);
                
                // 连接建立处理
                appData.websocket.onopen = function(event) {
                    console.log('WebSocket连接已建立');
                    const statusElem = document.getElementById('connection-status');
                    statusElem.innerHTML = '<i class="fas fa-circle text-green-500 mr-1 text-xs"></i> 已连接';
                };
                
                // 接收消息处理
                appData.websocket.onmessage = function(event) {
                    try {
                        const data = JSON.parse(event.data);
                        
                        // 处理不同类型的消息
                        if (data.type === 'wind_data') {
                            // 更新风速数据
                            const { station_id, timestamp, wind_speed } = data.data;
                            
                            if (!appData.stationData[station_id]) {
                                appData.stationData[station_id] = [];
                            }
                            
                            // 添加新的数据点
                            const newDataPoint = {
                                timestamp: timestamp,
                                windSpeed: wind_speed
                            };
                            
                            appData.stationData[station_id].push(newDataPoint);
                            
                            // 限制数据点数量
                            if (appData.stationData[station_id].length > 1000) {
                                appData.stationData[station_id].shift();
                            }
                            
                            // 更新UI
                            updateStationCard(station_id);
                            updateTrendChart();
                            
                        } else if (data.type === 'alert') {
                            // 处理报警消息
                            appData.alerts.unshift(data.data);
                            
                            // 限制报警数量
                            if (appData.alerts.length > 100) {
                                appData.alerts.pop();
                            }
                            
                            // 更新UI
                            updateAlerts();
                            
                        } else if (data.type === 'station_status') {
                            // 更新站点状态
                            const { station_id, status } = data.data;
                            
                            if (appData.stations[station_id]) {
                                appData.stations[station_id].status = status;
                                updateStationCard(station_id);
                            }
                        }
                        
                    } catch (err) {
                        console.error('处理WebSocket消息失败:', err);
                    }
                };
                
                // 连接关闭处理
                appData.websocket.onclose = function(event) {
                    console.log('WebSocket连接已关闭:', event.code, event.reason);
                    const statusElem = document.getElementById('connection-status');
                    statusElem.innerHTML = '<i class="fas fa-circle text-red-500 mr-1 text-xs"></i> 已断开';
                    
                    // 5秒后尝试重新连接
                    setTimeout(setupWebSocket, 5000);
                };
                
                // 错误处理
                appData.websocket.onerror = function(error) {
                    console.error('WebSocket错误:', error);
                    const statusElem = document.getElementById('connection-status');
                    statusElem.innerHTML = '<i class="fas fa-circle text-red-500 mr-1 text-xs"></i> 连接错误';
                };
                
            } catch (error) {
                console.error('建立WebSocket连接失败:', error);
                const statusElem = document.getElementById('connection-status');
                statusElem.innerHTML = '<i class="fas fa-circle text-red-500 mr-1 text-xs"></i> 连接失败';
            }
        }
        
        // 生成模拟数据
        function generateMockData() {
            console.log('生成模拟数据...');
            
            // 模拟站点数据
            appData.stations = {
                'A': { id: 'A', name: '站点A', location: '北部山区', status: 'online' },
                'B': { id: 'B', name: '站点B', location: '南部平原', status: 'online' },
                'C': { id: 'C', name: '站点C', location: '东部海岸', status: 'warning' },
                'D': { id: 'D', name: '站点D', location: '西部沙漠', status: 'offline' }
            };
            
            // 模拟风速数据
            appData.stationData = {};
            const timeRange = document.getElementById('time-selector').value;
            const now = new Date();
            
            // 为每个站点生成数据
            Object.keys(appData.stations).forEach(stationId => {
                const data = [];
                let points = 0;
                
                // 根据时间范围确定数据点数
                if (timeRange === 'hour') {
                    points = 60;  // 每分钟1个点
                } else if (timeRange === 'day') {
                    points = 24;  // 每小时1个点
                    } else {
                    points = 7;   // 每天1个点
                }
                
                // 生成数据点
                for (let i = 0; i < points; i++) {
                    let timestamp;
                    
                    if (timeRange === 'hour') {
                        timestamp = new Date(now.getTime() - (points - i) * 60 * 1000);
                    } else if (timeRange === 'day') {
                        timestamp = new Date(now.getTime() - (points - i) * 60 * 60 * 1000);
            } else {
                        timestamp = new Date(now.getTime() - (points - i) * 24 * 60 * 60 * 1000);
                    }
                    
                    // 基础风速
                    let baseWindSpeed = 0;
                    if (stationId === 'A') baseWindSpeed = 5;
                    if (stationId === 'B') baseWindSpeed = 3;
                    if (stationId === 'C') baseWindSpeed = 8;
                    if (stationId === 'D') baseWindSpeed = 2;
                    
                    // 添加随机变化
                    const variation = Math.random() * 5 - 2.5;
                    const windSpeed = Math.max(0, baseWindSpeed + variation);
                    
                    data.push({
                        timestamp: timestamp.toISOString(),
                        windSpeed: windSpeed
                    });
                }
                
                appData.stationData[stationId] = data;
            });
            
            // 模拟报警数据
            appData.alerts = [
                {
                    id: 1,
                    timestamp: new Date(now.getTime() - 15 * 60 * 1000).toISOString(),
                    stationId: 'C',
                    windSpeed: 12.5,
                    level: 'warning',
                    message: '站点C风速超过警戒值'
                },
                {
                    id: 2,
                    timestamp: new Date(now.getTime() - 45 * 60 * 1000).toISOString(),
                    stationId: 'A',
                    windSpeed: 10.2,
                    level: 'warning',
                    message: '站点A风速超过警戒值'
                },
                {
                    id: 3,
                    timestamp: new Date(now.getTime() - 3 * 60 * 60 * 1000).toISOString(),
                    stationId: 'D',
                    windSpeed: 0,
                    level: 'error',
                    message: '站点D连接丢失'
                }
            ];
            
            // 更新UI
            createStationCards();
            updateAlerts();
            updateTrendChart();
            
            // 如果简易地图已创建，则更新地图
            if (document.querySelector('.simple-map-container')) {
                createSimpleStationMap();
            }
            
            console.log('模拟数据生成完成');
        }
        
        // 创建站点卡片
        function createStationCards() {
            console.log('创建站点卡片...');
            const container = document.getElementById('station-cards');
            
            // 检查是否有站点数据
            if (!appData.stations || Object.keys(appData.stations).length === 0) {
                container.innerHTML = `
                    <div class="col-span-full text-center py-8 bg-gray-800 rounded-lg">
                        <i class="fas fa-exclamation-circle text-yellow-500 text-3xl mb-2"></i>
                        <p>没有站点数据可用</p>
                        <button id="load-mock-data" class="mt-4 px-4 py-2 bg-blue-600 hover:bg-blue-500 rounded-md">
                            加载模拟数据
                        </button>
                    </div>
                `;
                
                // 添加模拟数据加载按钮事件
                document.getElementById('load-mock-data').addEventListener('click', () => {
                    generateMockData();
                });
                
                return;
            }
            
            // 清空容器
            container.innerHTML = '';
            
            // 为每个站点创建卡片
            Object.values(appData.stations).forEach(station => {
                // 获取最新风速数据
                let latestData = { windSpeed: '暂无数据', timestamp: null };
                if (appData.stationData[station.id] && appData.stationData[station.id].length > 0) {
                    latestData = appData.stationData[station.id][appData.stationData[station.id].length - 1];
                }
                
                // 确定站点状态和对应颜色
                let statusClass = '';
                let statusColor = '';
                let statusText = '';
                
                if (station.status === 'online') {
                    statusClass = 'bg-blue-500';
                    statusColor = 'blue';
                    statusText = '在线';
                } else if (station.status === 'warning') {
                    statusClass = 'bg-yellow-500';
                    statusColor = 'yellow';
                    statusText = '警告';
                } else {
                    statusClass = 'bg-red-500';
                    statusColor = 'red';
                    statusText = '离线';
                }
                
                // 创建卡片HTML
                const card = document.createElement('div');
                card.id = `station-card-${station.id}`;
                card.className = `station-card bg-gray-800 rounded-lg shadow-lg overflow-hidden ${getStationBgClass(station.id)}`;
                card.style.borderLeft = `4px solid ${getStationColor(station.id)}`;
                
                // 格式化时间
                let timeDisplay = '暂无数据';
                if (latestData.timestamp) {
                    const date = new Date(latestData.timestamp);
                    timeDisplay = `${date.getFullYear()}-${String(date.getMonth()+1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
                }
                
                card.innerHTML = `
                    <div class="p-4">
                    <div class="flex justify-between items-start">
                        <div>
                                <h3 class="text-xl font-bold">${station.name}</h3>
                                <p class="text-gray-400 text-sm">${station.location}</p>
                        </div>
                            <span class="text-xs px-2 py-1 ${statusClass} rounded-full">${statusText}</span>
                    </div>
                        
                        <div class="mt-4 flex items-end justify-between">
                            <div>
                                <p class="text-gray-400 text-xs">当前风速</p>
                                <p class="text-3xl font-bold">
                                    ${typeof latestData.windSpeed === 'number' ? latestData.windSpeed.toFixed(1) : latestData.windSpeed}
                                    <span class="text-sm text-gray-400">m/s</span>
                                </p>
                            </div>
                            <div class="text-right">
                                <p class="text-gray-400 text-xs">更新时间</p>
                                <p class="text-sm">${timeDisplay}</p>
                            </div>
                        </div>
                        
                        <div class="mt-4 pt-4 border-t border-gray-700">
                            <button class="view-details-btn w-full py-2 text-center rounded-md bg-gray-700 hover:bg-gray-600 transition-colors" 
                                    data-station-id="${station.id}">
                                <i class="fas fa-chart-line mr-2"></i>查看详情
                            </button>
                        </div>
                    </div>
                `;
                
                container.appendChild(card);
                
                // 添加查看详情按钮事件
                card.querySelector('.view-details-btn').addEventListener('click', function() {
                    const stationId = this.getAttribute('data-station-id');
                    window.location.href = `station.html?id=${stationId}`;
                });
            });
            
            console.log('站点卡片创建完成');
        }
        
        // 更新单个站点卡片
        function updateStationCard(stationId) {
            const card = document.getElementById(`station-card-${stationId}`);
            if (!card) return;
            
            const station = appData.stations[stationId];
            if (!station) return;
            
            // 获取最新风速数据
            let latestData = { windSpeed: '暂无数据', timestamp: null };
            if (appData.stationData[stationId] && appData.stationData[stationId].length > 0) {
                latestData = appData.stationData[stationId][appData.stationData[stationId].length - 1];
            }
            
            // 确定站点状态和对应颜色
            let statusClass = '';
            let statusText = '';
            
            if (station.status === 'online') {
                statusClass = 'bg-blue-500';
                statusText = '在线';
            } else if (station.status === 'warning') {
                statusClass = 'bg-yellow-500';
                statusText = '警告';
                                } else {
                statusClass = 'bg-red-500';
                statusText = '离线';
            }
            
            // 更新状态标签
            const statusBadge = card.querySelector('.rounded-full');
            statusBadge.className = `text-xs px-2 py-1 ${statusClass} rounded-full`;
            statusBadge.textContent = statusText;
                                
                                // 更新风速显示
            const windSpeedElement = card.querySelector('.text-3xl');
            windSpeedElement.innerHTML = `
                ${typeof latestData.windSpeed === 'number' ? latestData.windSpeed.toFixed(1) : latestData.windSpeed}
                <span class="text-sm text-gray-400">m/s</span>
            `;
            
            // 更新时间显示
            let timeDisplay = '暂无数据';
            if (latestData.timestamp) {
                const date = new Date(latestData.timestamp);
                timeDisplay = `${date.getFullYear()}-${String(date.getMonth()+1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
            }
            
            const timeElement = card.querySelector('.text-right .text-sm');
            timeElement.textContent = timeDisplay;
        }
        
        // 更新报警列表
        function updateAlerts() {
            console.log('更新报警列表...');
            const container = document.getElementById('alert-container');
            
            // 检查是否有报警数据
            if (!appData.alerts || appData.alerts.length === 0) {
                container.innerHTML = `
                    <div class="text-center text-gray-500 py-6">
                        <i class="fas fa-check-circle text-2xl mb-2"></i>
                        <p>目前没有任何报警</p>
                    </div>
                `;
                return;
            }
            
            // 清空容器
            container.innerHTML = '';
            
            // 生成报警项
            appData.alerts.forEach(alert => {
                const date = new Date(alert.timestamp);
                const formattedTime = `${date.getFullYear()}-${String(date.getMonth()+1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
                
                // 决定报警颜色
                let alertClass = '';
                let icon = '';
                
                if (alert.level === 'warning') {
                    alertClass = 'border-yellow-500 bg-yellow-900/20';
                    icon = '<i class="fas fa-exclamation-triangle text-yellow-500"></i>';
                } else {
                    alertClass = 'border-red-500 bg-red-900/20';
                    icon = '<i class="fas fa-exclamation-circle text-red-500"></i>';
                }
                
                // 创建报警项
                const alertItem = document.createElement('div');
                alertItem.className = `mb-3 p-3 border-l-4 ${alertClass} rounded`;
                
                // 使用站点名称
                let stationName = alert.stationId;
                if (appData.stations[alert.stationId]) {
                    stationName = appData.stations[alert.stationId].name;
                }
                
                alertItem.innerHTML = `
                    <div class="flex items-start">
                        <div class="mr-3 mt-1">
                            ${icon}
                        </div>
                        <div class="flex-1">
                            <div class="flex justify-between items-start">
                                <p class="font-medium">${stationName}</p>
                                <span class="text-xs text-gray-400">${formattedTime}</span>
                            </div>
                            <p class="text-sm text-gray-300 mt-1">${alert.message}</p>
                            ${alert.windSpeed ? `<p class="text-sm font-bold mt-1">风速: ${alert.windSpeed.toFixed(1)} m/s</p>` : ''}
                        </div>
                    </div>
                `;
                
                container.appendChild(alertItem);
            });
            
            console.log('报警列表更新完成');
        }
        
        // 更新趋势图表
        function updateTrendChart() {
            console.log('更新趋势图表...');
            const container = document.getElementById('trend-chart');
            
            // 清空加载状态
            container.innerHTML = '';
            
            // 创建图表
            const chart = echarts.init(container);
            
            // 准备数据
            const series = [];
            const stationIds = Object.keys(appData.stations);
            
            // 检查是否有数据
            let hasData = false;
            stationIds.forEach(id => {
                if (appData.stationData[id] && appData.stationData[id].length > 0) {
                    hasData = true;
                }
            });
            
            if (!hasData) {
                container.innerHTML = `
                    <div class="absolute inset-0 flex items-center justify-center">
                        <div class="text-center text-gray-500">
                            <i class="fas fa-chart-line text-3xl mb-2"></i>
                            <p>暂无图表数据</p>
                        </div>
                    </div>
                `;
                return;
            }
            
            // 为每个站点生成系列数据
            stationIds.forEach(id => {
                if (!appData.stationData[id] || appData.stationData[id].length === 0) return;
                
                const station = appData.stations[id];
                const data = appData.stationData[id].map(item => [
                    new Date(item.timestamp),
                    item.windSpeed
                ]);
                
                series.push({
                    name: station.name,
                    type: 'line',
                    data: data,
                    symbol: 'circle',
                    symbolSize: 6,
                    showSymbol: false,
                    lineStyle: {
                        width: 3
                    },
                    itemStyle: {
                        color: getStationColor(id)
                    }
                });
            });
            
            // 图表选项
            const option = {
                backgroundColor: 'transparent',
                tooltip: {
                    trigger: 'axis',
                    formatter: function(params) {
                        const date = new Date(params[0].value[0]);
                        const formattedTime = `${date.getFullYear()}-${String(date.getMonth()+1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
                        
                        let html = `<div style="font-weight:bold">${formattedTime}</div>`;
                        
                        params.forEach(param => {
                            html += `<div style="display:flex;align-items:center;margin-top:5px">
                                <span style="display:inline-block;width:10px;height:10px;border-radius:50%;background-color:${param.color};margin-right:5px"></span>
                                <span>${param.seriesName}: ${param.value[1].toFixed(1)} m/s</span>
                            </div>`;
                        });
                        
                        return html;
                    }
                },
                legend: {
                    data: stationIds.map(id => appData.stations[id].name),
                    textStyle: {
                        color: '#eee'
                    },
                    right: '10%',
                    top: '0%'
                },
                grid: {
                    left: '3%',
                    right: '4%',
                    bottom: '3%',
                    top: '50px',
                    containLabel: true
                },
                xAxis: {
                    type: 'time',
                    axisLine: {
                        lineStyle: {
                            color: '#6B7280'
                        }
                    },
                    axisLabel: {
                        color: '#D1D5DB'
                    },
                    splitLine: {
                        show: false
                    }
                },
                yAxis: {
                    type: 'value',
                    name: '风速 (m/s)',
                    nameTextStyle: {
                        color: '#D1D5DB'
                    },
                    axisLine: {
                        lineStyle: {
                            color: '#6B7280'
                        }
                    },
                    axisLabel: {
                        color: '#D1D5DB'
                    },
                    splitLine: {
                        lineStyle: {
                            color: '#374151'
                        }
                    }
                },
                series: series
            };
            
            // 设置图表选项
            chart.setOption(option);
            
            // 保存图表实例以便后续更新
            appData.echartsInstance = chart;
            
            // 添加窗口大小变化监听器
            window.addEventListener('resize', function() {
                if (appData.echartsInstance) {
                    appData.echartsInstance.resize();
                }
            });
            
            console.log('趋势图表更新完成');
        }
        
        // 创建站点分布图（3D地形效果版）
        function createSimpleStationMap() {
            console.log('创建3D地形站点分布图...');
            const mapContainer = document.getElementById('map-container');
            
            if (!mapContainer) {
                console.error('找不到地图容器元素!');
                return;
            }
            
            // 清空容器内容
            mapContainer.innerHTML = '';
            
            // 创建3D分布图的容器
            const simpleMapContainer = document.createElement('div');
            simpleMapContainer.className = 'simple-map-container h-full w-full relative rounded-lg overflow-hidden';
            simpleMapContainer.style.background = 'radial-gradient(ellipse at center, #1a365d 0%, #0f2346 70%, #0a192f 100%)';
            mapContainer.appendChild(simpleMapContainer);
            
            // 添加3D效果容器
            const mapScene = document.createElement('div');
            mapScene.className = 'map-3d-scene';
            simpleMapContainer.appendChild(mapScene);

            // 添加地图平面
            const mapPlane = document.createElement('div');
            mapPlane.className = 'map-3d-plane';
            mapScene.appendChild(mapPlane);
            
            // 添加网格背景
            const gridOverlay = document.createElement('div');
            gridOverlay.className = 'grid-overlay';
            mapPlane.appendChild(gridOverlay);
            
            // 添加地形特征
            const terrainContainer = document.createElement('div');
            terrainContainer.className = 'terrain-container';
            mapPlane.appendChild(terrainContainer);
            
            // 添加山区
            const mountainArea = document.createElement('div');
            mountainArea.className = 'terrain-area mountain-area';
            mountainArea.innerHTML = `
                <div class="terrain-feature mountain mountain-1"></div>
                <div class="terrain-feature mountain mountain-2"></div>
                <div class="terrain-feature mountain mountain-3"></div>
                <div class="terrain-label">北部山区</div>
            `;
            terrainContainer.appendChild(mountainArea);
            
            // 添加平原
            const plainArea = document.createElement('div');
            plainArea.className = 'terrain-area plain-area';
            plainArea.innerHTML = `
                <div class="terrain-feature plain"></div>
                <div class="terrain-label">南部平原</div>
            `;
            terrainContainer.appendChild(plainArea);
            
            // 添加海岸
            const coastArea = document.createElement('div');
            coastArea.className = 'terrain-area coast-area';
            coastArea.innerHTML = `
                <div class="terrain-feature coast"></div>
                <div class="terrain-feature ocean"></div>
                <div class="terrain-label">东部海岸</div>
            `;
            terrainContainer.appendChild(coastArea);
            
            // 添加沙漠
            const desertArea = document.createElement('div');
            desertArea.className = 'terrain-area desert-area';
            desertArea.innerHTML = `
                <div class="terrain-feature desert"></div>
                <div class="terrain-label">西部沙漠</div>
            `;
            terrainContainer.appendChild(desertArea);
            
            // 修改样式
            const style = document.createElement('style');
            style.textContent = `
                .simple-map-container {
                    position: relative;
                    transition: all 0.5s ease;
                    box-shadow: 0 0 30px rgba(0, 30, 60, 0.5) inset;
                    perspective: 1200px;
                    overflow: hidden;
                }
                
                .map-3d-scene {
                    position: absolute;
                    top: 0;
                    left: 0;
                    width: 100%;
                    height: 100%;
                    transform-style: preserve-3d;
                    perspective-origin: 50% 50%;
                    transition: transform 1s ease;
                }
                
                .map-3d-plane {
                    position: absolute;
                    top: 0;
                    left: 0;
                    width: 100%;
                    height: 100%;
                    transform: rotateX(30deg) rotateY(0deg) translateZ(0px);
                    transform-style: preserve-3d;
                    background: linear-gradient(to bottom, rgba(10, 25, 47, 0.7), rgba(10, 25, 47, 0.9));
                    background-blend-mode: overlay;
                    box-shadow: 0 20px 80px rgba(0, 0, 0, 0.5);
                }
                
                .grid-overlay {
                    position: absolute;
                    top: 0;
                    left: 0;
                    width: 100%;
                    height: 100%;
                    background-image: 
                        linear-gradient(rgba(255, 255, 255, 0.03) 1px, transparent 1px),
                        linear-gradient(90deg, rgba(255, 255, 255, 0.03) 1px, transparent 1px);
                    background-size: 50px 50px;
                    z-index: 1;
                    transform: translateZ(2px);
                }
                
                .terrain-container {
                    position: absolute;
                    top: 0;
                    left: 0;
                    width: 100%;
                    height: 100%;
                    transform-style: preserve-3d;
                    z-index: 2;
                }
                
                .terrain-area {
                    position: absolute;
                    transform-style: preserve-3d;
                }
                
                .terrain-feature {
                    position: absolute;
                    transform-style: preserve-3d;
                    transform-origin: center center;
                }
                
                .terrain-label {
                    position: absolute;
                    color: rgba(255, 255, 255, 0.7);
                    font-size: 12px;
                    font-weight: bold;
                    text-shadow: 0 1px 3px rgba(0, 0, 0, 0.5);
                    transform: translateZ(30px);
                    white-space: nowrap;
                }
                
                /* 山区 */
                .mountain-area {
                    top: 10%;
                    left: 30%;
                    width: 40%;
                    height: 30%;
                }
                
                .mountain {
                    background: linear-gradient(135deg, #4B5563 10%, #1F2937 80%);
                    border-radius: 5px;
                    box-shadow: 0 5px 15px rgba(0, 0, 0, 0.5);
                }
                
                .mountain-1 {
                    width: 100px;
                    height: 100px;
                    clip-path: polygon(50% 0%, 80% 90%, 20% 90%);
                    transform: translateZ(40px);
                    left: 40%;
                    top: 10%;
                }
                
                .mountain-2 {
                    width: 80px;
                    height: 80px;
                    clip-path: polygon(50% 0%, 85% 90%, 15% 90%);
                    transform: translateZ(30px);
                    left: 20%;
                    top: 15%;
                }
                
                .mountain-3 {
                    width: 70px;
                    height: 70px;
                    clip-path: polygon(50% 0%, 80% 90%, 20% 90%);
                    transform: translateZ(35px);
                    left: 60%;
                    top: 20%;
                }
                
                .mountain-area .terrain-label {
                    top: 60%;
                    left: 40%;
                }
                
                /* 平原 */
                .plain-area {
                    top: 50%;
                    left: 60%;
                    width: 30%;
                    height: 30%;
                }
                
                .plain {
                    width: 100%;
                    height: 100%;
                    background: linear-gradient(to bottom, #2F855A 0%, #276749 100%);
                    transform: translateZ(5px);
                    border-radius: 50%;
                    opacity: 0.5;
                }
                
                .plain-area .terrain-label {
                    top: 50%;
                    left: 35%;
                }
                
                /* 海岸 */
                .coast-area {
                    top: 60%;
                    left: 70%;
                    width: 30%;
                    height: 40%;
                }
                
                .coast {
                    width: 80%;
                    height: 60%;
                    background: linear-gradient(to right, #2D3748, #4299E1);
                    transform: translateZ(3px);
                    border-radius: 50% 0 0 0;
                    top: 40%;
                    left: 20%;
                }
                
                .ocean {
                    width: 40%;
                    height: 40%;
                    background: linear-gradient(135deg, #4299E1, #2B6CB0);
                    transform: translateZ(2px);
                    border-radius: 0 50% 0 0;
                    top: 20%;
                    left: 60%;
                    animation: ocean-wave 8s infinite alternate;
                }
                
                @keyframes ocean-wave {
                    0% {
                        transform: translateZ(2px) translateY(0);
                    }
                    100% {
                        transform: translateZ(2px) translateY(-5px);
                    }
                }
                
                .coast-area .terrain-label {
                    top: 30%;
                    left: 50%;
                }
                
                /* 沙漠 */
                .desert-area {
                    top: 40%;
                    left: 15%;
                    width: 30%;
                    height: 40%;
                }
                
                .desert {
                    width: 100%;
                    height: 100%;
                    background: linear-gradient(45deg, #D69E2E 0%, #F6E05E 100%);
                    transform: translateZ(8px);
                    border-radius: 40%;
                    opacity: 0.6;
                }
                
                .desert-area .terrain-label {
                    top: 45%;
                    left: 35%;
                }
                
                /* 站点标记样式调整 */
                .station-marker {
                    position: absolute;
                    width: 48px;
                    height: 48px;
                    border-radius: 50%;
                    transform: translate3d(-50%, -50%, 30px);
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    font-weight: bold;
                    font-size: 18px;
                    color: white;
                    cursor: pointer;
                    transition: all 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.275);
                    z-index: 20;
                    animation: float-marker 3s ease-in-out infinite alternate;
                    border: 2px solid white;
                    box-shadow: 
                        0 0 0 4px rgba(255, 255, 255, 0.1),
                        0 5px 15px rgba(0, 0, 0, 0.4),
                        0 10px 20px rgba(0, 0, 0, 0.2);
                    transform-style: preserve-3d;
                }
                
                /* 调整站点A的高度 - 山区 */
                .station-marker[data-station-id="A"] {
                    transform: translate3d(-50%, -50%, 60px);
                }
                .station-marker[data-station-id="A"]:hover {
                    transform: translate3d(-50%, -50%, 70px) scale3d(1.15, 1.15, 1.15);
                }
                
                /* 调整站点B的高度 - 平原 */
                .station-marker[data-station-id="B"] {
                    transform: translate3d(-50%, -50%, 20px);
                }
                .station-marker[data-station-id="B"]:hover {
                    transform: translate3d(-50%, -50%, 30px) scale3d(1.15, 1.15, 1.15);
                }
                
                /* 调整站点C的高度 - 海岸 */
                .station-marker[data-station-id="C"] {
                    transform: translate3d(-50%, -50%, 15px);
                }
                .station-marker[data-station-id="C"]:hover {
                    transform: translate3d(-50%, -50%, 25px) scale3d(1.15, 1.15, 1.15);
                }
                
                /* 调整站点D的高度 - 沙漠 */
                .station-marker[data-station-id="D"] {
                    transform: translate3d(-50%, -50%, 25px);
                }
                .station-marker[data-station-id="D"]:hover {
                    transform: translate3d(-50%, -50%, 35px) scale3d(1.15, 1.15, 1.15);
                }
                
                @keyframes float-marker {
                    0% {
                        transform: translate3d(-50%, -50%, var(--base-height, 30px));
                    }
                    100% {
                        transform: translate3d(-50%, -50%, calc(var(--base-height, 30px) + 10px));
                    }
                }
                
                .station-marker:before {
                    content: '';
                    position: absolute;
                    width: 100%;
                    height: 100%;
                    border-radius: 50%;
                    background: inherit;
                    opacity: 0.4;
                    animation: pulse-ring 2s infinite;
                    transform: translateZ(-5px);
                }
                
                .station-marker:after {
                    content: '';
                    position: absolute;
                    bottom: -15px;
                    left: 50%;
                    width: 50%;
                    height: 5px;
                    border-radius: 50%;
                    background: rgba(0, 0, 0, 0.4);
                    filter: blur(4px);
                    transform: translateX(-50%) rotateX(90deg) translateZ(-5px);
                }
                
                @keyframes pulse-ring {
                    0% {
                        transform: scale3d(0.8, 0.8, 1);
                        opacity: 0.4;
                    }
                    50% {
                        transform: scale3d(1.2, 1.2, 1);
                        opacity: 0.1;
                    }
                    100% {
                        transform: scale3d(0.8, 0.8, 1);
                        opacity: 0.4;
                    }
                }
                
                .station-marker:hover {
                    z-index: 30;
                }
                
                .map-title {
                    text-align: center;
                    padding: 15px;
                    color: white;
                    font-weight: bold;
                    font-size: 20px;
                    text-shadow: 0 2px 4px rgba(0, 0, 0, 0.5);
                    position: absolute;
                    top: 5px;
                    left: 0;
                    right: 0;
                    z-index: 100;
                    transform: translateZ(80px);
                }
            `;
            document.head.appendChild(style);
            
            // 添加标题
            const title = document.createElement('div');
            title.className = 'map-title';
            title.innerHTML = '风速监测站点分布 <small style="font-size: 12px; opacity: 0.7;">3D地形图</small>';
            simpleMapContainer.appendChild(title);
            
            // 站点坐标 - 在容器中的百分比位置，并匹配地形特征
            const stationPositions = {
                'A': { x: 50, y: 25, name: '站点A', location: '北部山区' },
                'B': { x: 75, y: 65, name: '站点B', location: '南部平原' },
                'C': { x: 85, y: 70, name: '站点C', location: '东部海岸' },
                'D': { x: 25, y: 60, name: '站点D', location: '西部沙漠' }
            };
            
            // 确保appData.stations存在
            if (!appData.stations || Object.keys(appData.stations).length === 0) {
                // 如果没有站点数据，使用模拟数据
                appData.stations = {
                    'A': { id: 'A', name: '站点A', location: '北部山区', status: 'online' },
                    'B': { id: 'B', name: '站点B', location: '南部平原', status: 'online' },
                    'C': { id: 'C', name: '站点C', location: '东部海岸', status: 'warning' },
                    'D': { id: 'D', name: '站点D', location: '西部沙漠', status: 'offline' }
                };
            }
            
            // 过滤不存在的站点
            let orderedStationIds = ['A', 'B', 'C', 'D'].filter(id => 
                Object.keys(appData.stations).includes(id));
            
            // 添加连接线
            orderedStationIds.forEach(id => {
                orderedStationIds.forEach(targetId => {
                    if (targetId !== id && stationPositions[targetId]) {
                        const line = document.createElement('div');
                        line.className = 'station-line';
                        
                        // 计算线的长度和角度
                        const x1 = stationPositions[id].x;
                        const y1 = stationPositions[id].y;
                        const x2 = stationPositions[targetId].x;
                        const y2 = stationPositions[targetId].y;
                        
                        const length = Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2));
                        const angle = Math.atan2(y2 - y1, x2 - x1) * 180 / Math.PI;
                        
                        // 设置高度差，根据地形
                        let z1 = 10;
                        let z2 = 10;
                        
                        if (id === 'A') z1 = 60;
                        else if (id === 'B') z1 = 20;
                        else if (id === 'C') z1 = 15;
                        else if (id === 'D') z1 = 25;
                        
                        if (targetId === 'A') z2 = 60;
                        else if (targetId === 'B') z2 = 20;
                        else if (targetId === 'C') z2 = 15;
                        else if (targetId === 'D') z2 = 25;
                        
                        // 取中间高度
                        const zMid = (z1 + z2) / 2;
                        
                        line.style.width = `${length}%`;
                        line.style.left = `${x1}%`;
                        line.style.top = `${y1}%`;
                        line.style.height = '2px';
                        // 3D变换根据地形高度
                        line.style.transform = `rotateZ(${angle}deg) translateZ(${zMid}px)`;
                        line.style.background = `linear-gradient(90deg, 
                          rgba(59, 130, 246, 0.3), 
                          rgba(59, 130, 246, 0.5), 
                          rgba(59, 130, 246, 0.3))`;
                        
                        mapPlane.appendChild(line);
                    }
                });
            });
            
            // 添加站点标记
            orderedStationIds.forEach(id => {
                const station = appData.stations[id];
                if (!station) return;
                
                // 获取最新风速数据
                let windSpeed = '加载中...';
                if (appData.stationData && appData.stationData[id] && appData.stationData[id].length > 0) {
                    windSpeed = appData.stationData[id][appData.stationData[id].length - 1].windSpeed.toFixed(1);
                }
                
                // 创建站点标记
                const marker = document.createElement('div');
                marker.className = `station-marker ${station.status || 'online'}`;
                marker.setAttribute('data-station-id', id);
                marker.style.left = `${stationPositions[id].x}%`;
                marker.style.top = `${stationPositions[id].y}%`;
                marker.textContent = id;
                
                // 根据地形设置基础高度
                let baseHeight = 30;
                if (id === 'A') baseHeight = 60; // 山区
                else if (id === 'B') baseHeight = 20; // 平原
                else if (id === 'C') baseHeight = 15; // 海岸
                else if (id === 'D') baseHeight = 25; // 沙漠
                
                marker.style.setProperty('--base-height', `${baseHeight}px`);
                
                // 创建站点标题
                const title = document.createElement('div');
                title.className = 'station-title';
                title.innerHTML = `
                    <div>${station.name}</div>
                    <div class="station-info">
                        <i class="fas fa-map-marker-alt mr-1"></i>${station.location}
                    </div>
                    <div class="station-info">
                        <i class="fas fa-wind mr-1"></i>风速：${windSpeed} m/s
                    </div>
                `;
                
                // 添加点击事件
                marker.addEventListener('click', () => {
                    window.location.href = `station.html?id=${id}`;
                });
                
                marker.appendChild(title);
                mapPlane.appendChild(marker);
                
                // 添加风速数据标签
                const dataBadge = document.createElement('div');
                dataBadge.className = 'wind-data-badge';
                dataBadge.style.left = `${stationPositions[id].x + (Math.random() * 10 - 5)}%`;
                dataBadge.style.top = `${stationPositions[id].y - (Math.random() * 10 + 8)}%`;
                dataBadge.style.transform = `translate3d(-50%, -50%, ${baseHeight + 10}px)`;
                dataBadge.innerHTML = `${windSpeed} m/s`;
                mapPlane.appendChild(dataBadge);
            });
            
            // 添加图例
            const legend = document.createElement('div');
            legend.className = 'simple-map-legend';
            legend.innerHTML = `
                <div class="legend-title">站点状态</div>
                <div class="legend-item">
                    <div class="legend-color" style="background: linear-gradient(135deg, #10B981, #059669);"></div>
                    <span>在线</span>
                </div>
                <div class="legend-item">
                    <div class="legend-color" style="background: linear-gradient(135deg, #F59E0B, #D97706);"></div>
                    <span>警告</span>
                </div>
                <div class="legend-item">
                    <div class="legend-color" style="background: linear-gradient(135deg, #EF4444, #B91C1C);"></div>
                    <span>离线</span>
                </div>
                <div style="margin-top: 10px; border-top: 1px solid rgba(255, 255, 255, 0.1); padding-top: 10px;">
                    <div class="legend-title">地形分布</div>
                    <div class="legend-item">
                        <div class="legend-color" style="background: linear-gradient(135deg, #4B5563, #1F2937);"></div>
                        <span>山区</span>
                    </div>
                    <div class="legend-item">
                        <div class="legend-color" style="background: linear-gradient(135deg, #2F855A, #276749);"></div>
                        <span>平原</span>
                    </div>
                    <div class="legend-item">
                        <div class="legend-color" style="background: linear-gradient(135deg, #4299E1, #2B6CB0);"></div>
                        <span>海岸</span>
                    </div>
                    <div class="legend-item">
                        <div class="legend-color" style="background: linear-gradient(135deg, #D69E2E, #F6E05E);"></div>
                        <span>沙漠</span>
                    </div>
                </div>
            `;
            simpleMapContainer.appendChild(legend);
            
            // 添加视角控制
            const viewControls = document.createElement('div');
            viewControls.className = 'view-controls';
            viewControls.innerHTML = `
                <button id="view-reset" title="重置视角"><i class="fas fa-sync-alt"></i></button>
                <button id="view-rotate-left" title="向左旋转"><i class="fas fa-arrow-left"></i></button>
                <button id="view-rotate-right" title="向右旋转"><i class="fas fa-arrow-right"></i></button>
                <button id="view-rotate-up" title="向上旋转"><i class="fas fa-arrow-up"></i></button>
                <button id="view-rotate-down" title="向下旋转"><i class="fas fa-arrow-down"></i></button>
            `;
            simpleMapContainer.appendChild(viewControls);
            
            // 添加地图模式切换按钮
            const mapModeSwitch = document.createElement('div');
            mapModeSwitch.className = 'map-mode-switch';
            mapModeSwitch.innerHTML = `
                <div class="map-mode-btn active" data-mode="simple">3D地形图</div>
                <div class="map-mode-btn" data-mode="china">中国地图</div>
            `;
            simpleMapContainer.appendChild(mapModeSwitch);
            
            // 添加3D视角控制功能
            let currentRotateX = 30;
            let currentRotateY = 0;
            let currentTranslateZ = 0;
            
            const updateMapPlaneTransform = () => {
                mapPlane.style.transform = `rotateX(${currentRotateX}deg) rotateY(${currentRotateY}deg) translateZ(${currentTranslateZ}px)`;
            };
            
            // 重置视角
            document.getElementById('view-reset').addEventListener('click', () => {
                currentRotateX = 30;
                currentRotateY = 0;
                currentTranslateZ = 0;
                updateMapPlaneTransform();
            });
            
            // 向左旋转
            document.getElementById('view-rotate-left').addEventListener('click', () => {
                currentRotateY -= 5;
                updateMapPlaneTransform();
            });
            
            // 向右旋转
            document.getElementById('view-rotate-right').addEventListener('click', () => {
                currentRotateY += 5;
                updateMapPlaneTransform();
            });
            
            // 向上旋转
            document.getElementById('view-rotate-up').addEventListener('click', () => {
                currentRotateX = Math.max(5, currentRotateX - 5);
                updateMapPlaneTransform();
            });
            
            // 向下旋转
            document.getElementById('view-rotate-down').addEventListener('click', () => {
                currentRotateX = Math.min(60, currentRotateX + 5);
                updateMapPlaneTransform();
            });
            
            // 添加鼠标拖拽控制
            let isDragging = false;
            let lastMouseX = 0;
            let lastMouseY = 0;
            
            mapScene.addEventListener('mousedown', (e) => {
                isDragging = true;
                lastMouseX = e.clientX;
                lastMouseY = e.clientY;
            });
            
            document.addEventListener('mousemove', (e) => {
                if (isDragging) {
                    const deltaX = e.clientX - lastMouseX;
                    const deltaY = e.clientY - lastMouseY;
                    
                    currentRotateY += deltaX * 0.5;
                    currentRotateX = Math.max(5, Math.min(60, currentRotateX - deltaY * 0.5));
                    
                    updateMapPlaneTransform();
                    
                    lastMouseX = e.clientX;
                    lastMouseY = e.clientY;
                }
            });
            
            document.addEventListener('mouseup', () => {
                isDragging = false;
            });
            
            // 添加鼠标滚轮控制缩放
            mapScene.addEventListener('wheel', (e) => {
                e.preventDefault();
                const delta = Math.sign(e.deltaY);
                currentTranslateZ -= delta * 20;
                currentTranslateZ = Math.max(-100, Math.min(50, currentTranslateZ));
                updateMapPlaneTransform();
            });
            
            // 添加切换事件
            const modeBtns = mapModeSwitch.querySelectorAll('.map-mode-btn');
            modeBtns.forEach(btn => {
                btn.addEventListener('click', function() {
                    // 移除所有按钮的active类
                    modeBtns.forEach(b => b.classList.remove('active'));
                    // 给当前按钮添加active类
                    this.classList.add('active');
                    
                    const mode = this.getAttribute('data-mode');
                    if (mode === 'china') {
                        // 显示加载消息
                        const loadingMsg = document.createElement('div');
                        loadingMsg.className = 'map-loading-msg';
                        loadingMsg.style.position = 'absolute';
                        loadingMsg.style.top = '50%';
                        loadingMsg.style.left = '50%';
                        loadingMsg.style.transform = 'translate(-50%, -50%)';
                        loadingMsg.style.background = 'rgba(0, 0, 0, 0.7)';
                        loadingMsg.style.padding = '10px 20px';
                        loadingMsg.style.borderRadius = '8px';
                        loadingMsg.style.zIndex = '100';
                        loadingMsg.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i>正在加载中国地图...';
                        simpleMapContainer.appendChild(loadingMsg);
                        
                        // 尝试加载中国地图
                        loadEchartsMap()
                            .then(() => {
                                initMap();
                            })
                            .catch(err => {
                                console.error('加载中国地图失败:', err);
                                loadingMsg.innerHTML = '地图加载失败，请检查网络连接<br><small>继续使用3D地形图</small>';
                                setTimeout(() => {
                                    loadingMsg.remove();
                                }, 3000);
                            });
                    }
                });
            });
            
            console.log('3D地形站点分布图创建完成');
            return simpleMapContainer;
        }
        
        // 更新时间显示
        function updateTime() {
            const now = new Date();
            document.getElementById('current-time').textContent = 
                `更新时间: ${now.getFullYear()}-${String(now.getMonth()+1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')} ${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}`;
        }
        
        // 加载ECharts地图
        async function loadEchartsMap() {
            return new Promise((resolve, reject) => {
                // 检查是否已加载
                if (echarts.getMap('china')) {
                    resolve();
                return;
            }
            
                // 加载中国地图
                const script = document.createElement('script');
                script.src = 'https://cdn.jsdelivr.net/npm/echarts@5.4.0/map/js/china.js';
                script.onload = () => {
                    appData.echartsLoaded = true;
                    console.log('中国地图加载成功');
                    resolve();
                };
                script.onerror = (err) => {
                    console.error('中国地图加载失败:', err);
                    reject(err);
                };
                document.head.appendChild(script);
            });
        }
        
        // 获取站点颜色
        function getStationColor(stationId) {
            // 固定颜色映射，与图表中显示的一致
            const colors = {
                'A': '#3B82F6', // 站点A - 蓝色
                'B': '#10B981', // 站点B - 绿色
                'C': '#F59E0B', // 站点C - 黄/橙色
                'D': '#8B5CF6'  // 站点D - 紫色
            };
            return colors[stationId] || '#6B7280';
        }

        // 获取站点背景样式
        function getStationBgClass(stationId) {
            const classes = {
                'A': 'bg-blue-600/20',
                'B': 'bg-green-600/20',
                'C': 'bg-yellow-600/20',
                'D': 'bg-purple-600/20'
            };
            return classes[stationId] || 'bg-gray-600/20';
        }
        
        // 尝试加载地图
        function loadMap() {
            // 获取地图容器
            const mapContainer = document.getElementById('map-container');
            
            if (mapContainer) {
                // 创建SVG地图
                createSVGMap(mapContainer, appData.stations);
            } else {
                console.error('找不到地图容器元素!');
            }
        }
        
        // 初始化页面 
        document.addEventListener('DOMContentLoaded', () => {
            initPage();
            updateTime();
            setInterval(updateTime, 60000);
            
            // 使用SVG地图替代原来的简易地图
            loadMap();
            
            // 粒子效果初始化
            particlesJS('particles-js', {
                particles: {
                    number: { value: 80, density: { enable: true, value_area: 800 } },
                    color: { value: "#ffffff" },
                    shape: { type: "circle" },
                    opacity: { value: 0.5, random: true },
                    size: { value: 3, random: true },
                    line_linked: { enable: true, distance: 150, color: "#ffffff", opacity: 0.4, width: 1 },
                    move: { enable: true, speed: 2, direction: "none", random: true, straight: false, out_mode: "out" }
                },
                interactivity: {
                    detect_on: "canvas",
                    events: {
                        onhover: { enable: true, mode: "repulse" },
                        onclick: { enable: true, mode: "push" }
                    }
                }
            });
        });
    </script>
</body>
</html>

